<?php
/**
 * Created by PhpStorm.
 * User: Hong
 * Date: 2018/3/24
 * Time: 15:33
 * Function:
 */

namespace Admin\Controllers\Organizes;
use Admin\Controllers\BaseAdminController;
use Organize\Policies\LeaderPolicy;
use Organize\Resources\RoleResources;
use Illuminate\Http\Request;
use Platform\Models\Organize\LeaderPermission;
use Platform\Models\Organize\LeaderRole;
use Platform\Models\Organize\Organize;
use Platform\Repository\Organize\LeaderRoleRepository;
use Platform\System\Tools\ResultTool;

/**
 *   组织角色管理
 * Class RoleController
 * @package App\Http\Controllers\Admin\System
 */
class OrganizeRoleController extends BaseAdminController
{

    /**
     * @var LeaderRoleRepository
     */
    protected $repository;

    /**
     * @var LeaderPolicy
     */
    protected $policy;

    /**
     * @var Organize
     */
    protected $organize;

    public function __construct(LeaderRoleRepository $repository, LeaderPolicy $policy){
        parent::__construct();
        $this->repository = $repository;
        $this->policy = $policy;
    }

    /**
     *   组织角色列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $this->getOrganize();
        $roles = $this->repository->screen($request,$this->organize);
        return myResult()->setData($roles)->send();
    }

    /**
     *  创建角色
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $this->getOrganize();
        $data = $this->verify($request);

        if ($data['is_default'] == LeaderRole::DEFAULT_YES){
            $this->repository->clearDefault($this->organize);
        }

        $role = LeaderRole::create($data);

        if ($role && is_array($request->get('permissions'))) {
            $permissionIds = array_filter($request->get('permissions'));
            foreach ($permissionIds as $key => $id){
                $permission = LeaderPermission::find($id);
                if (!$permission) unset($permissionIds[$key]);
            }
            $role->permissions()->sync($permissionIds);
        }

        return myResult()->setCode(ResultTool::CODE_SUCCESS,'角色创建成功')->send();
    }

    /**
     *  角色详情
     *
     * @param LeaderRole $role
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function show(LeaderRole $role)
    {
        $role->load('permissions');
        return myResult()->setData($role,RoleResources::class)->send();
    }

    /**
     * 更新角色
     *
     * @param Request $request
     * @param LeaderRole $role
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, LeaderRole $role)
    {
        $this->getOrganize($role->organize);

        $data = $this->verify($request,$role);

        if ($data['is_default'] == LeaderRole::DEFAULT_YES){
            $this->repository->clearDefault($this->organize);
        }

        $role->update($data);

        $permissionIds = array_filter($request->get('permissions'));
        if (!empty($permissionIds)) {
            foreach ($permissionIds as $key => $id){
                $permission = LeaderPermission::find($id);
                if (!$permission) unset($permissionIds[$key]);
            }
            $role->permissions()->sync($permissionIds);
            LeaderPermission::refreshCache();
        }


        return myResult()->setCode(ResultTool::CODE_SUCCESS,'角色编辑成功')->send();
    }

    /**
     * 删除角色
     *
     * @param LeaderRole $role
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(LeaderRole $role)
    {
        if ($role->is_default)
            myResult()->stop(ResultTool::CODE_TARGET_WRONG,'默认角色不可删除');

        $role->permissions()->detach();
        $role->leaders()->where('role_id',$role->id)->update(['role_id' => null]);
        LeaderPermission::refreshCache();
        $role->delete();

        return myResult()->setCode(ResultTool::CODE_SUCCESS,'删除成功')->send();
    }

    /**
     * 数据验证
     * @param Request $request
     * @param LeaderRole|null $role
     * @return array
     */
    public function verify(Request $request,LeaderRole $role = null){
        $data = $request->only(['name','describe']);

        $data['is_default'] = in_array($request->is_default,[LeaderRole::DEFAULT_YES,LeaderRole::DEFAULT_NO]) ? $request->is_default : LeaderRole::DEFAULT_NO;

        if (empty($data['name'])) myResult()->stop(ResultTool::CODE_PARAM_LOST,'名称不可为空');

        if (getStrLength($data['name']) > 20) myResult()->stop(ResultTool::CODE_PARAM_WRONG,'名称过长');

        if ($role){
            if ($role->is_default == LeaderRole::DEFAULT_YES  && $data['is_default'] == LeaderRole::DEFAULT_NO){
                $role_log = $this->repository->getDefault($this->organize, $role->id);
                if (!$role_log)
                    myResult()->stop(ResultTool::CODE_TARGET_WRONG,'组织内必须存在一个默认角色');
            }
            $role_log = $this->repository->getOneByName($this->organize, $data['name'], $role->id);
        }else{
            $role_log = $this->repository->getOneByName($this->organize, $data['name']);
        }
        if ($role_log) myResult()->stop(ResultTool::CODE_TARGET_WRONG,'角色名称已存在');


        $data['organize_id'] = $this->organize->id;
        return $data;
    }
}